package com.mxy.myapplication2.service

import android.app.Notification
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import com.mxy.myapplication2.R
import com.mxy.myapplication2.java.Util
import com.mxy.myapplication2.kotlin.SocketClientActivity
import com.mxy.myapplication2.util.IsWebCanBeUse
import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * Socket客户端
 */
class SocketClient : Service() {

    private val socketHostAddress = "192.168.2.173"
    private val socketHostPort = 9999
    private val clientDisconnect = "clientDisconnect"
    private val wifiChangeReceiver: WifiChangeReceiver = WifiChangeReceiver()
    private val receiveclientSendMessageToSocketServer: ReceiveClientSendMessageToSocketServer = ReceiveClientSendMessageToSocketServer()
    private val executorService: ExecutorService = Executors.newCachedThreadPool()
    private lateinit var notificationbuilder: NotificationCompat.Builder
    //是否继续循环心跳
    private var isLoop: Boolean = true

    override fun onCreate() {
        super.onCreate()

        //监听WIFI连接情况
        val filter = IntentFilter()
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(wifiChangeReceiver, filter)

        val intentFilter = IntentFilter()
        intentFilter.addAction(SocketClientActivity.sendMessageAction)
        registerReceiver(receiveclientSendMessageToSocketServer, intentFilter)

        notificationbuilder = NotificationCompat.Builder(this, socketHostPort.toString())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        this.startForeground(socketHostPort, getNotification())

        executorService.execute(BeginHeartBeat())

        return START_STICKY
    }


    override fun onDestroy() {
        super.onDestroy()
        isLoop = false
        unregisterReceiver(wifiChangeReceiver)
        unregisterReceiver(receiveclientSendMessageToSocketServer)
        executorService.execute(ClientHeartBeatThread(clientDisconnect))
        this.stopForeground(true)
    }

    /**
     * 有新消息
     * */
    fun newMessage(newContent: String) {
        val newClientIntent = Intent(SocketClientActivity.newContentReceiverAction)
        newClientIntent.putExtra(SocketClientActivity.newContentReceiverAction, newContent)
        sendBroadcast(newClientIntent)
    }


    /**
     * 监控网络变更 WIFI关闭就结束服务
     * */
    inner class WifiChangeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (!IsWebCanBeUse.isWIFIConnection(context)) {
                newMessage("WIFI已断开Socket自动停止")
                stopService(Intent(context, SocketServer::class.java))
            }
        }
    }

    /**
     * 监听客户端发送消息到服务器
     * */
    inner class ReceiveClientSendMessageToSocketServer : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val message = intent!!.getStringExtra(SocketClientActivity.sendMessageAction)
            if (message != null && !"".equals(message)) {
                executorService.execute(ClientHeartBeatThread(message))
            }
        }
    }

    inner class BeginHeartBeat : Runnable {

        override fun run() {
            while (isLoop) {
                //启动心跳
                executorService.execute(ClientHeartBeatThread("正常心跳"))
                //间隔1秒
                Thread.sleep(1 * 1000)
            }
        }

    }


    inner class ClientHeartBeatThread constructor(sendMessage: String) : Runnable {

        private val sendMessage: String

        init {
            this.sendMessage = sendMessage
        }

        override fun run() {

            try {
                val client = Socket(socketHostAddress, socketHostPort)
                val bufferedWriter = BufferedWriter(OutputStreamWriter(client.getOutputStream()))
                bufferedWriter.write(this.sendMessage)
                bufferedWriter.flush()
                //写入完毕单方面关闭输出流
                client.shutdownOutput()
                val receiveMessage = Util.convertStreamToStringUtf8(client)
                //输入输出流都处理完毕后，统一关闭socket
                client.close()
                newMessage(receiveMessage)//将读取到的数据发送给客户端UI界面
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 自定义通知栏
     *
     * @return
     */
    private fun getNotification(): Notification {
        //        notificationbuilder.setTicker("动漫之家");//状态栏消息滚动说明
        notificationbuilder.setContentTitle("SocketClient")
        notificationbuilder.setContentText("SocketClient已启动")
        notificationbuilder.setWhen(System.currentTimeMillis()) //时间
        //android 6.0以上，SmallIcon需要使用白色图标，否则android会把不透明的部分全部绘制成白色
        notificationbuilder.setSmallIcon(R.drawable.eye)
        //        Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
        //        notificationbuilder.setLargeIcon(bitmap);
        notificationbuilder.setAutoCancel(true)
        //        notificationbuilder.setProgress(100,10,false);//设置带进度条的通知栏 前提是使用默认通知栏布局

        //5.0以上横幅消息推送
        //情况1:设置消息优先级 从Android 5.0开始，如果notification  priority设置为HIGH, MAX,并且设置了notificationbuilder.setDefaults(NotificationCompat.DEFAULT_ALL)
        //情况2:设置setfullscreenintent();
        notificationbuilder.setPriority(NotificationCompat.PRIORITY_MAX)
        notificationbuilder.setOngoing(true)//设置为一个正在进行的通知，属于后台任务
//        notificationbuilder.setCustomContentView(getSmallRemoteView())
//        notificationbuilder.setCustomBigContentView(getBigRemoteViews())
        /**
         * 设置可见性
         *
         * 您的应用可以控制在安全锁定屏幕上显示的通知中可见的详细级别。 调用 setVisibility() 并指定以下值之一：
         *
         * VISIBILITY_PUBLIC 显示通知的完整内容。
         * VISIBILITY_SECRET 不会在锁定屏幕上显示此通知的任何部分。
         * VISIBILITY_PRIVATE 显示通知图标和内容标题等基本信息，但是隐藏通知的完整内容。
         * 设置 VISIBILITY_PRIVATE 后，您还可以提供其中隐藏了某些详细信息的替换版本通知内容。
         * 例如，短信 应用可能会显示一条通知，指出“您有 3 条新短信”，但是隐藏了短信内容和发件人。
         * 要提供此替换版本的通知，请先使用 NotificationCompat.Builder 创建替换通知。创建专用通知对象时，请通过 setPublicVersion() 方法为其附加替换通知。
         */
        notificationbuilder.setVisibility(Notification.VISIBILITY_PUBLIC)//锁屏界面显示
//        notificationbuilder.setContentIntent(notificationClick())
        //        notificationbuilder.setDefaults(NotificationCompat.DEFAULT_ALL);//声音+震动+呼吸灯
        return notificationbuilder.build()
    }

    override fun onBind(intent: Intent?): IBinder {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}